package com.qf.test;

import com.qf.utils.ESUtil;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.search.SimpleQueryStringQueryParser;
import org.junit.Test;

import java.io.IOException;

/**
 * 创建索引并添加数据结构
 */
public class IndexDemo {


    @Test   //  /person
    public void createIndex() throws IOException {
        //1. 创建指定的Request对象，并设置索引名称
        CreateIndexRequest request = new CreateIndexRequest("person");

        //2. 设置添加的数据给Request对象
        //2.1 settings
        Settings settings = Settings.builder()
                .put("number_of_shards",5)
                .put("number_of_replicas",1)
                .build();
        //2.2 mappings
        XContentBuilder mappings = JsonXContent.contentBuilder()
                .startObject()
                    .startObject("properties")
                        .startObject("name")
                            .field("type","text")
                            .field("analyzer","ik_max_word")
                        .endObject()
                        .startObject("author")
                            .field("type","text")
                            .field("analyzer","ik_max_word")
                        .endObject()
                        .startObject("count")
                            .field("type","long")
                        .endObject()
                        .startObject("date")
                            .field("type","date")
                            .field("format","yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis")
                        .endObject()
                    .endObject()
                .endObject();
        //2.3 设置给request
        request.settings(settings);
        request.mapping(mappings);

        //3. 通过连接对象将Request发送给ES，并接受Response
        CreateIndexResponse resp = ESUtil.getClient().indices().create(request, RequestOptions.DEFAULT);
        //4. 通过Response判断添加是否成功
        System.out.println(resp.isAcknowledged());
    }


}
